<template>
    <div class="login_container">
        <el-dialog v-model="userStore.visible" title="用户登录" @closed="dialogClosed">
            <div class="content">
                <el-row>
                    <el-col :span="12">
                        <div class="login">
                            <div class="wechat" v-show="wechatLogin">
                                <div id='login_container'></div>
                                <div class="phone">
                                    <p>手机短信验证码登录</p>
                                    <svg @click="changeLogin" t="1711640612387" class="icon" viewBox="0 0 1024 1024"
                                        version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4398" width="32"
                                        height="32">
                                        <path
                                            d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                                            p-id="4399" fill="#e98f36"></path>
                                    </svg>
                                </div>
                            </div>
                            <div v-show="!wechatLogin">
                                <el-form ref="loginForm" :model="loginParam" :rules="rules">
                                    <el-form-item prop="phone">
                                        <el-input placeholder="请输入手机号码" :prefix-icon="User"
                                            v-model="loginParam.phone" />
                                    </el-form-item>
                                    <el-form-item prop="code">
                                        <div class="code-examine">
                                            <el-input placeholder="请输入验证码" :prefix-icon="Lock" v-model="loginParam.code"
                                                style="width: 70%;" />
                                            <el-button type="primary" size="default" :disabled="!isPhone || flag"
                                                @click="clickCodeButton" style="width: 25%;">
                                                <CountDown v-if="flag" @close-flag="changeFlag"></CountDown>
                                                <span v-else>获取验证码</span>
                                            </el-button>
                                        </div>
                                    </el-form-item>
                                </el-form>
                                <div class="bottom">
                                    <el-button style="width:100%" type="primary"
                                        :disabled="!isPhone || loginParam.code == ''" size="default"
                                        @click="clickLoginButton(loginForm)">用户登录</el-button>
                                    <p>微信扫码登录</p>
                                    <svg @click="changeLogin" t="1711114258506" class="icon" viewBox="0 0 1024 1024"
                                        version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4297" width="32"
                                        height="32">
                                        <path
                                            d="M337.387283 341.82659c-17.757225 0-35.514451 11.83815-35.514451 29.595375s17.757225 29.595376 35.514451 29.595376 29.595376-11.83815 29.595376-29.595376c0-18.49711-11.83815-29.595376-29.595376-29.595375zM577.849711 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763zM501.641618 401.017341c17.757225 0 29.595376-12.578035 29.595376-29.595376 0-17.757225-11.83815-29.595376-29.595376-29.595375s-35.514451 11.83815-35.51445 29.595375 17.757225 29.595376 35.51445 29.595376zM706.589595 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763z"
                                            fill="#28C445" p-id="4298"></path>
                                        <path
                                            d="M510.520231 2.959538C228.624277 2.959538 0 231.583815 0 513.479769s228.624277 510.520231 510.520231 510.520231 510.520231-228.624277 510.520231-510.520231-228.624277-510.520231-510.520231-510.520231zM413.595376 644.439306c-29.595376 0-53.271676-5.919075-81.387284-12.578034l-81.387283 41.433526 22.936416-71.768786c-58.450867-41.433526-93.965318-95.445087-93.965317-159.815029 0-113.202312 105.803468-201.988439 233.803468-201.98844 114.682081 0 216.046243 71.028902 236.023121 166.473989-7.398844-0.739884-14.797688-1.479769-22.196532-1.479769-110.982659 1.479769-198.289017 85.086705-198.289017 188.67052 0 17.017341 2.959538 33.294798 7.398844 49.572255-7.398844 0.739884-15.537572 1.479769-22.936416 1.479768z m346.265896 82.867052l17.757225 59.190752-63.630058-35.514451c-22.936416 5.919075-46.612717 11.83815-70.289017 11.83815-111.722543 0-199.768786-76.947977-199.768786-172.393063-0.739884-94.705202 87.306358-171.653179 198.289017-171.65318 105.803468 0 199.028902 77.687861 199.028902 172.393064 0 53.271676-34.774566 100.624277-81.387283 136.138728z"
                                            fill="#28C445" p-id="4299"></path>
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="12" class="ad">
                        <div class="rightContent">
                            <div class="top">
                                <div class="item">
                                    <img src="../../assets/images/code_app.png" alt="" />
                                    <svg t="1685263287521" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                        xmlns="http://www.w3.org/2000/svg" p-id="2450" width="16" height="16">
                                        <path
                                            d="M337.387283 341.82659c-17.757225 0-35.514451 11.83815-35.514451 29.595375s17.757225 29.595376 35.514451 29.595376 29.595376-11.83815 29.595376-29.595376c0-18.49711-11.83815-29.595376-29.595376-29.595375zM577.849711 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763zM501.641618 401.017341c17.757225 0 29.595376-12.578035 29.595376-29.595376 0-17.757225-11.83815-29.595376-29.595376-29.595375s-35.514451 11.83815-35.51445 29.595375 17.757225 29.595376 35.51445 29.595376zM706.589595 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763z"
                                            fill="#cdcdcd" p-id="2451"></path>
                                        <path
                                            d="M510.520231 2.959538C228.624277 2.959538 0 231.583815 0 513.479769s228.624277 510.520231 510.520231 510.520231 510.520231-228.624277 510.520231-510.520231-228.624277-510.520231-510.520231-510.520231zM413.595376 644.439306c-29.595376 0-53.271676-5.919075-81.387284-12.578034l-81.387283 41.433526 22.936416-71.768786c-58.450867-41.433526-93.965318-95.445087-93.965317-159.815029 0-113.202312 105.803468-201.988439 233.803468-201.98844 114.682081 0 216.046243 71.028902 236.023121 166.473989-7.398844-0.739884-14.797688-1.479769-22.196532-1.479769-110.982659 1.479769-198.289017 85.086705-198.289017 188.67052 0 17.017341 2.959538 33.294798 7.398844 49.572255-7.398844 0.739884-15.537572 1.479769-22.936416 1.479768z m346.265896 82.867052l17.757225 59.190752-63.630058-35.514451c-22.936416 5.919075-46.612717 11.83815-70.289017 11.83815-111.722543 0-199.768786-76.947977-199.768786-172.393063-0.739884-94.705202 87.306358-171.653179 198.289017-171.65318 105.803468 0 199.028902 77.687861 199.028902 172.393064 0 53.271676-34.774566 100.624277-81.387283 136.138728z"
                                            fill="#cdcdcd" p-id="2452"></path>
                                    </svg>
                                    <p>微信扫一扫关注</p>
                                    <p>“快速预约挂号”</p>
                                </div>
                                <div class="item">
                                    <img src="../../assets/images/code_login_wechat.png" alt="" />
                                    <svg t="1685263518283" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                        xmlns="http://www.w3.org/2000/svg" p-id="3668" width="16" height="16">
                                        <path
                                            d="M256 85.333333h512c64.8 0 117.333333 52.533333 117.333333 117.333334v618.666666c0 64.8-52.533333 117.333333-117.333333 117.333334H256c-64.8 0-117.333333-52.533333-117.333333-117.333334V202.666667c0-64.8 52.533333-117.333333 117.333333-117.333334z m0 64a53.333333 53.333333 0 0 0-53.333333 53.333334v618.666666a53.333333 53.333333 0 0 0 53.333333 53.333334h512a53.333333 53.333333 0 0 0 53.333333-53.333334V202.666667a53.333333 53.333333 0 0 0-53.333333-53.333334H256z m170.666667 618.666667a32 32 0 0 1 0-64h170.666666a32 32 0 0 1 0 64H426.666667z"
                                            fill="#000000" p-id="3669"></path>
                                    </svg>
                                    <p>扫一扫下载</p>
                                    <p>“预约挂号”APP</p>
                                </div>
                            </div>
                            <div class="bottom">
                                <p class="tip">“医盏明灯”医院合作平台</p>
                                <p class="tip">快速挂号 安全放心</p>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <template #footer>
                <el-button type="primary" size="default" @click="userStore.visible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="Login">
// 引入微信扫码登录的参数请求接口及数据类型
import { reqWxLogin } from '@/api/hospital/index'
import { WXLoginResponseData } from '@/api/hospital/type';
// 获取仓库中控制显隐的数据
import { useUserStore } from "@/store/modules/user";
import { User, Lock } from '@element-plus/icons-vue'
import type { FormRules, FormInstance } from 'element-plus'
import { onMounted, ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
// 引入倒计时组件
import CountDown from "@/components/countdown/index.vue";
import { useRoute, useRouter } from 'vue-router';


const userStore = useUserStore();
//获取路由器对象
const $router = useRouter();
const $route = useRoute()

// 是否用微信登录
const wechatLogin = ref<boolean>(false);

// 收集表单数据-手机号码
const loginParam = reactive({
    phone: '',
    code: '',
})

// 表单组件引用对象
const loginForm = ref<FormInstance>();

// 控制倒计时组件的显隐
const flag = ref<boolean>(false);

//计算出当前表单元素收集的内容是否手机号码格式
const isPhone = computed(() => {
    //手机号码正则表达式
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    //返回布尔值:真代表手机号码、假代表的即为不是手机号码
    return reg.test(loginParam.phone);
});
// 获取验证码按钮的回调函数
const clickCodeButton = async () => {
    // 开启倒计时组件
    flag.value = true;
    try {
        //获取验证码成功
        await userStore.getCode(loginParam.phone);
        setTimeout(() => {
            loginParam.code = userStore.code;
        }, 4000)

    } catch (error) {
        ElMessage({
            type: "error",
            message: (error as Error).message,
        });
    }
}

// 用户登录按钮的回调函数
const clickLoginButton = async (formEl: FormInstance | undefined) => {
    // 通过表单组件的validate方法进行表单校验
    if (!formEl) return
    await formEl.validate(async () => {
        try {
            // 发起登录请求
            // 若请求成功，顶部组件展示用户名字，登录对话框关闭
            // 若请求失败，则弹出登录失败的提示信息
            await userStore.userLogin(loginParam)

            // 登录成功，关闭对话框
            userStore.visible = false;

            // 添加鉴权后，用户存在登录后跳回原功能模块的需求
            // 获取url的query参数
            const redirect = $route.query.redirect;
            if (redirect) {
                $router.push(redirect as string);
            } else {
                $router.push('/home');
            }
        } catch (error) {
            // 登录失败，显示提示
            ElMessage({
                type: "error",
                message: (error as Error).message,
            });
        }
    })

}

// 更改倒计时组件的显隐 
const changeFlag = () => {
    flag.value = false;
}

//自定义校验规则:手机号码自定义校验
const validatorPhone = (_rule: any, value: any, callBack: any) => {
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    if (reg.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的手机号码格式"));
    }
};

//验证码自定义校验规则
const validatorCode = (_rule: any, value: any, callBack: any) => {
    //rule:即为表单校验规则对象
    //value:即为当前文本的内容
    //callBack:回调函数

    if (value === '') {
        callBack(new Error("请输入验证码"));
    }

    if (/^\d{6}$/.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的验证码格式"));
    }
};

//表单校验的规则对象
const rules = reactive<FormRules<typeof loginParam>>({
    //手机号码校验规则

    phone: [{ trigger: "change", validator: validatorPhone }],
    code: [{ trigger: "change", validator: validatorCode }],
});

// 切换微信登录
const changeLogin = async () => {
    wechatLogin.value = !wechatLogin.value;

    if (wechatLogin.value === true) {
        const redirect_url: string = encodeURIComponent(window.location.origin + '/wxlogin')
        // 请求参数
        const res: WXLoginResponseData = await reqWxLogin(redirect_url)
        //@ts-ignore
        const obj = new WxLogin({
            // true：手机点击确认登录后可以在 iframe 内跳转到 redirect_uri，false：手机点击确认登录后可以在 top window 跳转到 redirect_uri。默认为 false。
            self_redirect: true,
            // 第三方页面显示二维码的容器id
            id: "login_container",
            // 应用唯一标识，在微信开放平台提交应用审核通过后获得
            appid: res.data.appid,
            // 应用授权作用域，拥有多个作用域用逗号（,）分隔，网页应用目前仅填写snsapi_login即可
            scope: "snsapi_login",
            // 重定向地址，需要进行UrlEncode
            redirect_uri: res.data.redirectUri,
            // 用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
            state: res.data.state,
            // 提供"black"、"white"可选，默认为黑色文字描述。
            style: "",
            // 自定义样式链接，第三方可根据实际需求覆盖默认样式。
            href: ""
        });
    }
}

// 对话框结束关闭动画后的回调函数
const dialogClosed = () => {
    // 清空表单数据
    Object.assign(loginParam, { phone: '', code: '' })
    // 清空表单检验情况
    loginForm.value?.resetFields()
    wechatLogin.value = false
}

// 监听窗口当前的类型，如果是微信开启store内登录监视
watch(
    () => wechatLogin.value,
    (val: boolean) => {
        if (val) {
            userStore.queryState();
        }
    }
);

const wxLogin: any = watch(
    () => userStore.wxSuccess,
    (val: boolean) => {
        if (val) {
            wxLogin()
            // 添加鉴权后，用户存在登录后跳回原功能模块的需求
            // 获取url的query参数
            const redirect = $route.query.redirect;
            if (redirect) {
                $router.push(redirect as string);
            } else {
                $router.push('/home');
            }
        }
    }
);

onMounted(() => {

})
</script>

<style scoped lang="scss">
.login_container {
    :deep(.el-dialog__body) {
        border-top: 1px solid #ccc;
        border-bottom: 1px solid #ccc;
    }

    .content {
        margin: 30px 0;

        .login {
            border: 1px solid #ccc;
            padding: 20px;

            .wechat {
                display: flex;
                flex-direction: column;
                align-items: center;
                height: 400px;

                .phone {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    position: absolute;
                    background: white;
                    margin-top: 340px;
                    width: 320px;

                    p {
                        margin: 10px 0
                    }
                }
            }

            .code-examine {
                display: flex;
                justify-content: space-between;
                width: 100%;

                .el-input {
                    margin-right: 10px;
                }
            }

            .bottom {
                display: flex;
                flex-direction: column;
                align-items: center;

                p {
                    margin: 10px 0px;
                }

                svg {
                    cursor: pointer;
                }
            }
        }

        .ad {
            display: flex;
            align-items: center;
            justify-content: center;

            .rightContent {

                .top {
                    display: flex;
                    justify-content: space-around;

                    .item {
                        display: flex;
                        flex-direction: column;
                        align-items: center;

                        margin: 0 20px;

                        img {
                            width: 130px;
                        }

                        p {
                            margin: 5px 0;
                        }
                    }
                }

                .bottom {
                    margin-top: 10px;

                    p {
                        text-align: center;
                        margin: 15px 0;
                        font-size: 20px;
                        font-weight: 700;
                    }
                }
            }
        }
    }

}
</style>